package com.hmyd.hmyd_android.ui;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Bank;
import com.hmyd.hmyd_android.dto.SinaDetail;
import com.hmyd.hmyd_android.dto.WithdrawDetail;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 取款
 *
 */
@ContentView(R.layout.activity_assets_cash)
public class WithdrawalsActivity extends BasicActivity {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.relative_money)
	private RelativeLayout relative_money;
	@ViewInject(R.id.submit)
	private Button submit;
	
	// 取现金额
	@ViewInject(R.id.withdrawals)
	private EditText withdrawals;
	//平台提现管理费
	@ViewInject(R.id.managementFee)
	private TextView managementFee;
	//新浪支付手续费
	@ViewInject(R.id.sinaAmount)
	private TextView sinaAmount;
	//实际到账金额
	@ViewInject(R.id.realWithdrawAmount)
	private TextView realWithdrawAmount;
	// 取现说明
	@ViewInject(R.id.assets_cash_fee_description)
	private TextView assets_cash_fee_description;

	private static final String BANK = "bank";
	private static final String AVAILABLE_BALANCE = "available_balance";

	private WithdrawDetail withdrawDetail;
	private Bank bank;
	private String assetsAmount; 	
	private String bindingPayCardId;	//绑卡id

	private final int BANKCARD = 1;
	private final int DODEPOSIT = 2;
	private final int DOWITHDRAW = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		setSubmitColor(false);
	}

	private void onRequest(){
		onRequest(BANKCARD, UrlConstant.WITHDRAW, HttpMethod.POST, null);
	}

	// 取现说明
	@OnClick(R.id.assets_cash_fee_description)
	private void descriptionClick(View v){
		if(AppBasic.app!=null && !TextUtils.isEmpty(AppBasic.app.withdrawDepositInstructionsLinkUrl)){
			Utils.jumpURL(this, AppBasic.app.withdrawDepositInstructionsLinkUrl,
					getString(R.string.assets_cash_description),"",false);
		}
	}

	// 取现提交
	@OnClick(R.id.submit)
	private void submitClick(View v){

		RequestParams params = new RequestParams();
		params.addBodyParameter("withdrawId", withdrawDetail.withdrawId);
		params.addBodyParameter("bindingPayCardId", bindingPayCardId);
		params.addBodyParameter("availableDou", String.valueOf(assetsAmount));
		params.addBodyParameter("realWithdrawDou", String.valueOf(withdrawDetail.realWithdrawAmount));
		params.addBodyParameter("managementFeeDou", String.valueOf(withdrawDetail.managementFee));
		params.addBodyParameter("newDepositDou", String.valueOf(withdrawDetail.newDepositAmount));

		onRequest(DOWITHDRAW, UrlConstant.DOWITHDRAW, HttpMethod.POST, params);	//提现
	}

	ArrayList<Timer> timerList = new ArrayList<Timer>();
	final Handler verificationHandler = new Handler(){ 
		public void handleMessage(Message msg) {  
			switch (msg.what) {   
			case 0:
				relative_money.setVisibility(View.GONE);
				setSubmitColor(false);
				break;
			case 1:
				relative_money.setVisibility(View.GONE);
				MyToast.showHMToast(WithdrawalsActivity.this, false, msg.obj.toString());
				setSubmitColor(false);
				break;
			case 2:
				setSubmitColor(true);
				RequestParams params = new RequestParams();
				
				params.addBodyParameter("bindingPayCardId", bindingPayCardId);
				params.addBodyParameter("availableDou", String.valueOf(assetsAmount));
				params.addBodyParameter("withdrawDou", msg.obj.toString());
				
				onRequest(DODEPOSIT, UrlConstant.GENERATEWITHDRAWDETAIL, HttpMethod.POST, params);
				break;
			}
		}
	};
	
	private TextWatcher watcher = new TextWatcher() {

		@Override    
		public void afterTextChanged(final Editable s) {

			for(Timer _timer:timerList){
				_timer.cancel();
			}

			Timer timer = new Timer();
			timerList.add(timer);

			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					
					Message message = new Message();
					
					if(TextUtils.isEmpty(s.toString().trim())){
						message.what = 0;      
						verificationHandler.sendMessage(message); 

						return;
					}
					
					try {
						Double.parseDouble(s.toString().trim());
					} catch (Exception e) {
						message.what = 1;      
						message.obj = "提现金额格式有误";
						verificationHandler.sendMessage(message); 
						return;
					}
					
					try {
						double withdrawals_money = Double.parseDouble(s.toString().trim());
						double totalAmount = Double.valueOf(assetsAmount);
						
						if (withdrawals_money <= 2) {
							message.what = 1;
							message.obj = "提现金额必须2元以上";
							
							verificationHandler.sendMessage(message); 
							return;
						}
						
						if (withdrawals_money > totalAmount) {
							message.what = 1;
							message.obj = "提现金额大于当前余额，请重新确认提现金额！";
							
							verificationHandler.sendMessage(message); 
							return;
						}
						
						message.what = 2;
						message.obj = s.toString().trim();
						verificationHandler.sendMessage(message); 
					} catch (Exception e) {
						return;
					}
				}
			}, 800);
		}   

		@Override 
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}  

		@Override    
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}                    
	};

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		switch (postId) {
		case BANKCARD:
			java.lang.reflect.Type type2 = new TypeToken<Bank>() {}.getType();
			Bank bank = gson.fromJson(msg, type2);
//			setData(bank);
			bindingPayCardId = bank.cardId;
			break;
		case DODEPOSIT:
			java.lang.reflect.Type type3 = new TypeToken<WithdrawDetail>() {}.getType();
			withdrawDetail = gson.fromJson(msg, type3);
			if (withdrawDetail != null && withdrawDetail.list.size() > 0) {
				drawDetail();
			}
			break;
		case DOWITHDRAW:
			java.lang.reflect.Type type4 = new TypeToken<SinaDetail>() {}.getType();
			SinaDetail detail = gson.fromJson(msg, type4);
			if (null == detail) return;

			if (detail.code.equalsIgnoreCase("success")) {
				Utils.jumpURL(this, detail.message, "新浪平台管理提现", "", false);
				AppBasic.getInstance().finishActivity(this);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		switch (postId) {
		case BANKCARD:
			AppBasic.getInstance().finishCurrentActivity();
			break;
		}
	}
	
	/**
	 * 设置提交按钮是否可点击
	 * @param ispress 是否可以点击
	 */
	private void setSubmitColor(boolean ispress){
		submit.setFocusable(ispress);
		submit.setClickable(ispress);
		
		if (ispress) {
			submit.setBackgroundColor(getResources().getColor(R.color.radio_button_selected_color));
		} else {
			submit.setBackgroundColor(getResources().getColor(R.color.more_line_bg));
		}
	}

	private void drawDetail(){
		relative_money.setVisibility(View.VISIBLE);
		realWithdrawAmount.setText(Utils.amountConversionFormat(withdrawDetail.realWithdrawAmount)+"元");
		managementFee.setText(Utils.amountConversionFormat(withdrawDetail.managementFee)+"元");
		sinaAmount.setText(Utils.amountConversionFormat(withdrawDetail.sinaAmount)+"元");
	}

	/*private void setData(Bank bank){
		bindingPayCardId = bank.cardId;
	}*/

	@Override
	protected void setParams() {
		home_title_txt.setText(getString(R.string.assets_cash));
		home_right.setText(getString(R.string.assets_cash_detail));
		home_title.setOnTouchListener(touch);

		assetsAmount = getIntent().getStringExtra(AVAILABLE_BALANCE);

		String available_balance = getString(R.string.available_balance);
		String msg = String.format(available_balance, assetsAmount);

		SpannableStringBuilder style = new SpannableStringBuilder(msg);
		style.setSpan(
				new ForegroundColorSpan(getResources().getColor(R.color.text_orange)), 
				msg.indexOf(assetsAmount), 
				msg.indexOf(assetsAmount) + assetsAmount.length(), 
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE
				);
		
		withdrawals.setHint(style);
		
		bank = (Bank) getIntent().getSerializableExtra(BANK);
		if (null == bank) {
			onRequest();
		} else {
//			setData(bank);
			bindingPayCardId = bank.cardId;
		}

		withdrawals.addTextChangedListener(watcher);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		this.startActivity(new Intent(this, WithdrawalsHistoryListActivity.class));
	}

}
